<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="售后单号" prop="afterSalesNumber">
        <el-input
            v-model="queryParams.afterSalesNumber"
            placeholder="请输入售后单号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户ID" prop="membersId">
        <el-select
            v-model="queryParams.membersId"
            placeholder="请选择用户ID"
            clearable
            filterable
            remote
            :remote-method="remoteSearchMembers"
            :loading="membersLoading"
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in membersOptions"
              :key="item.id"
              :label="`${item.id}（${item.nickname}）`"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单商品项ID" prop="shopOrderItemId">
        <el-select
            v-model="queryParams.shopOrderItemId"
            placeholder="请选择订单商品项ID"
            clearable
            filterable
            remote
            :remote-method="remoteSearchOrderItems"
            :loading="orderItemsLoading"
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in orderItemsOptions"
              :key="item.id"
              :label="`${item.id}（${item.productName}）`"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="售后类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择售后类型" clearable style="width:200px">
          <el-option
              v-for="dict in after_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="售后状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择售后状态" clearable style="width:200px">
          <el-option
              v-for="dict in after_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="售后商品类型" prop="orderstatus">
        <el-select v-model="queryParams.orderstatus" placeholder="请选择售后商品类型" clearable style="width:200px">
          <el-option
              v-for="dict in after_orderstatus"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input
            v-model="queryParams.contactName"
            placeholder="请输入联系人姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="contactPhone">
        <el-input
            v-model="queryParams.contactPhone"
            placeholder="请输入联系电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退货/换货地址" prop="returnAddress">
        <el-input
            v-model="queryParams.returnAddress"
            placeholder="请输入退货/换货地址"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请售后商品数量" prop="quantity">
        <el-input
            v-model="queryParams.quantity"
            placeholder="请输入申请售后商品数量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="应退款金额" prop="refundAmount">
        <el-input
            v-model="queryParams.refundAmount"
            placeholder="请输入应退款金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实退金额" prop="actualRefundAmount">
        <el-input
            v-model="queryParams.actualRefundAmount"
            placeholder="请输入实退金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createdAt">
        <el-date-picker clearable
                        v-model="queryParams.createdAt"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updatedAt">
        <el-date-picker clearable
                        v-model="queryParams.updatedAt"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['transaction:YZMsales:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['transaction:YZMsales:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['transaction:YZMsales:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['transaction:YZMsales:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="YZMsalesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="售后申请ID" align="center" prop="id" />
      <el-table-column label="售后单号" align="center" prop="afterSalesNumber" />
      <el-table-column label="用户ID" prop="membersId">
        <template #default="scope">
    <span v-if="scope.row.members">
      {{ scope.row.members.id }}（{{ scope.row.members.nickname }}）
    </span>
          <span v-else>
      {{ scope.row.membersId }}
    </span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="订单商品项ID" align="center" prop="shopOrderItemId" />-->
      <el-table-column label="订单商品项ID" prop="shopOrderItemId">
        <template #default="scope">
    <span v-if="scope.row.shopOrderItem">
      {{ scope.row.shopOrderItem.id }}（{{ scope.row.shopOrderItem.productName }}）
    </span>
          <span v-else>
      {{ scope.row.shopOrderItemId }}
    </span>
        </template>
      </el-table-column>

      <el-table-column label="售后类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="after_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="售后状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="after_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="售后商品类型" align="center" prop="orderstatus">
        <template #default="scope">
          <dict-tag :options="after_orderstatus" :value="scope.row.orderstatus"/>
        </template>
      </el-table-column>
      <el-table-column label="联系人姓名" align="center" prop="contactName" />
      <el-table-column label="联系电话" align="center" prop="contactPhone" />
      <el-table-column label="退货/换货地址" align="center" prop="returnAddress" />
      <el-table-column label="申请售后商品数量" align="center" prop="quantity" />
      <el-table-column label="售后原因，如尺寸不符、质量问题等" align="center" prop="reason" />
      <el-table-column label="图片凭证" align="center" prop="proofImages" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.proofImages" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="应退款金额" align="center" prop="refundAmount" />
      <el-table-column label="实退金额" align="center" prop="actualRefundAmount" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['transaction:YZMsales:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['transaction:YZMsales:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改订单售后申请对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="YZMsalesRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="售后单号" prop="afterSalesNumber">
          <el-input v-model="form.afterSalesNumber" placeholder="请输入售后单号" />
        </el-form-item>
        <el-form-item label="用户ID" prop="membersId">
          <el-select
              v-model="form.membersId"
              placeholder="请选择用户ID"
              filterable
              remote
              :remote-method="remoteSearchMembers"
              :loading="membersLoading"
          >
            <el-option
                v-for="item in membersOptions"
                :key="item.id"
                :label="`${item.id}（${item.nickname}）`"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单商品项ID" prop="shopOrderItemId">
          <el-select
              v-model="form.shopOrderItemId"
              placeholder="请选择订单商品项ID"
              filterable
              remote
              :remote-method="remoteSearchOrderItems"
              :loading="orderItemsLoading"
          >
            <el-option
                v-for="item in orderItemsOptions"
                :key="item.id"
                :label="`${item.id}（${item.productName}）`"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="售后类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择售后类型">
            <el-option
                v-for="dict in after_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="售后状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择售后状态">
            <el-option
                v-for="dict in after_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="售后商品类型" prop="orderstatus">
          <el-select v-model="form.orderstatus" placeholder="请选择售后商品类型">
            <el-option
                v-for="dict in after_orderstatus"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="退货/换货地址" prop="returnAddress">
          <el-input v-model="form.returnAddress" placeholder="请输入退货/换货地址" />
        </el-form-item>
        <el-form-item label="申请售后商品数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入申请售后商品数量" />
        </el-form-item>
        <el-form-item label="售后原因，如尺寸不符、质量问题等" prop="reason">
          <el-input v-model="form.reason" placeholder="请输入售后原因，如尺寸不符、质量问题等" />
        </el-form-item>
        <el-form-item label="图片凭证" prop="proofImages">
          <image-upload v-model="form.proofImages"/>
        </el-form-item>
        <el-form-item label="应退款金额" prop="refundAmount">
          <el-input v-model="form.refundAmount" placeholder="请输入应退款金额" />
        </el-form-item>
        <el-form-item label="实退金额" prop="actualRefundAmount">
          <el-input v-model="form.actualRefundAmount" placeholder="请输入实退金额" />
        </el-form-item>
        <el-form-item label="逻辑删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入逻辑删除标志" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
                          v-model="form.createdAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
                          v-model="form.updatedAt"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="YZMsales">
import { listYZMsales, getYZMsales, delYZMsales, addYZMsales, updateYZMsales } from "@/api/transaction/YZMsales"
import { listShoporderitem } from "@/api/transaction/shoporderitem"
import { listMembers } from "@/api/core/members"
import { onMounted } from 'vue'

const { proxy } = getCurrentInstance()
const { after_type, after_orderstatus, after_status } = proxy.useDict('after_type', 'after_orderstatus', 'after_status')

const YZMsalesList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 新增的状态变量
const membersOptions = ref([])
const orderItemsOptions = ref([])
const membersLoading = ref(false)
const orderItemsLoading = ref(false)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    afterSalesNumber: null,
    membersId: null,
    shopOrderItemId: null,
    type: null,
    status: null,
    orderstatus: null,
    contactName: null,
    contactPhone: null,
    returnAddress: null,
    quantity: null,
    refundAmount: null,
    actualRefundAmount: null,
    createdAt: null,
    updatedAt: null
  },
  rules: {
    membersId: [{ required: true, message: "用户ID不能为空", trigger: "blur" }],
    shopOrderItemId: [{ required: true, message: "订单商品项ID不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 远程搜索用户方法
const remoteSearchMembers = async (query) => {
  membersLoading.value = true
  try {
    const response = await listMembers({
      pageNum: 1,
      pageSize: 100,
      nickName: query || undefined
    })
    membersOptions.value = response.rows || []
  } catch (error) {
    console.error("搜索用户失败:", error)
    membersOptions.value = []
  } finally {
    membersLoading.value = false
  }
}

// 远程搜索订单商品方法
const remoteSearchOrderItems = async (query) => {
  orderItemsLoading.value = true
  try {
    const response = await listShoporderitem({
      pageNum: 1,
      pageSize: 100,
      productName: query || undefined
    })
    orderItemsOptions.value = response.rows || []
  } catch (error) {
    console.error("搜索订单商品失败:", error)
    orderItemsOptions.value = []
  } finally {
    orderItemsLoading.value = false
  }
}

// 初始化加载数据
onMounted(() => {
  // 预加载一些数据
  remoteSearchMembers('')
  remoteSearchOrderItems('')
})

/** 查询订单售后申请列表 */
function getList() {
  loading.value = true
  listYZMsales(queryParams.value).then(response => {
    YZMsalesList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(error => {
    console.error("获取售后申请列表失败:", error)
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    afterSalesNumber: null,
    membersId: null,
    shopOrderItemId: null,
    type: null,
    status: null,
    orderstatus: null,
    contactName: null,
    contactPhone: null,
    returnAddress: null,
    quantity: null,
    reason: null,
    proofImages: null,
    refundAmount: null,
    actualRefundAmount: null,
    delFlag: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("YZMsalesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加订单售后申请"
  // 确保有最新的选项数据
  if (membersOptions.value.length === 0) {
    remoteSearchMembers('')
  }
  if (orderItemsOptions.value.length === 0) {
    remoteSearchOrderItems('')
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getYZMsales(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改订单售后申请"
    // 确保有最新的选项数据
    if (membersOptions.value.length === 0) {
      remoteSearchMembers('')
    }
    if (orderItemsOptions.value.length === 0) {
      remoteSearchOrderItems('')
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["YZMsalesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateYZMsales(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addYZMsales(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除订单售后申请编号为"' + _ids + '"的数据项？').then(function() {
    return delYZMsales(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('transaction/YZMsales/export', {
    ...queryParams.value
  }, `YZMsales_${new Date().getTime()}.xlsx`)
}

getList()
</script>